package com.utra.hellshan.upload.UI;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.DotOptions;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.trace.LBSTraceClient;
import com.baidu.trace.api.entity.AddEntityResponse;
import com.baidu.trace.api.entity.AroundSearchRequest;
import com.baidu.trace.api.entity.AroundSearchResponse;
import com.baidu.trace.api.entity.BoundSearchResponse;
import com.baidu.trace.api.entity.DeleteEntityResponse;
import com.baidu.trace.api.entity.DistrictSearchResponse;
import com.baidu.trace.api.entity.EntityInfo;
import com.baidu.trace.api.entity.EntityListRequest;
import com.baidu.trace.api.entity.EntityListResponse;
import com.baidu.trace.api.entity.FilterCondition;
import com.baidu.trace.api.entity.LocRequest;
import com.baidu.trace.api.entity.OnEntityListener;
import com.baidu.trace.api.entity.PolygonSearchResponse;
import com.baidu.trace.api.entity.SearchResponse;
import com.baidu.trace.api.entity.UpdateEntityResponse;
import com.baidu.trace.api.track.AddPointResponse;
import com.baidu.trace.api.track.AddPointsResponse;
import com.baidu.trace.api.track.ClearCacheTrackResponse;
import com.baidu.trace.api.track.DistanceResponse;
import com.baidu.trace.api.track.HistoryTrackRequest;
import com.baidu.trace.api.track.HistoryTrackResponse;
import com.baidu.trace.api.track.LatestPointRequest;
import com.baidu.trace.api.track.LatestPointResponse;
import com.baidu.trace.api.track.OnTrackListener;
import com.baidu.trace.api.track.QueryCacheTrackResponse;
import com.baidu.trace.api.track.TrackPoint;
import com.baidu.trace.model.CoordType;
import com.baidu.trace.model.ProcessOption;
import com.baidu.trace.model.TraceLocation;
import com.baidu.trace.model.TransportMode;
import com.utra.hellshan.upload.OtherTools.DataSplit;
import com.utra.hellshan.upload.OtherTools.ServiceTool;
import com.utra.hellshan.upload.OtherTools.SystemUtil;
import com.utra.hellshan.upload.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import services.StatusService;
import services.TrackService;

public class mapAvtivity extends Activity {

    private long serviceID = 202605;         //serviceID
    private String thisDevice = "99aaasd";      //本机实例名
    private MapView mapView ;
    private BaiduMap baiduMap;  //地图总控制器
    boolean lockMylocation = true;
    RelativeLayout relativeLayout;
    public static Boolean have_logged_in = false;                     /**需要用Intent进行操作**/
    TrackService trackService;
    LBSTraceClient client;
    LocationClient locationClient ;
    BDLocation bdLocation;

    boolean bindRoad = false;

    boolean testMode = false;

    ArrayList<String> names = new ArrayList<>();
    int entitycounts = 0 ;


    boolean show_thiscar = false;
    boolean show_all = true;
    long loctime = 0;

    int overSpeed = 0xff0c0c0c;
    int while_bg = 0xdee3e900;
    int safe = 0x38b44a00;
    int speed_alert = 40;   //超速阈值

    boolean alldone = false;

    com.getbase.floatingactionbutton.FloatingActionButton floatingActionButton;

    private boolean firstRun = true;
    private com.baidu.trace.model.LatLng mylocation = new com.baidu.trace.model.LatLng(0,0);
    private double aroundSearchRadius = 200;        //周边探测范围。默认5.5（不知道具体多大）


    ArrayList<EntityInfo> allinfo;           //周围实例全部信息，没有用，轨迹点用下边的allEntityTracePoints记录
    ArrayList<String> enitynames;        //周围实例名称
    ArrayList<TrackPoint>  trackPoints;     //记录一个实例的轨迹

    ArrayList<ArrayList<TrackPoint>> allEntityTracePoints;      //记录全部的实力的轨迹

    int flashTime = 8;
    long distanceTime = 15 ;      //暂定2分钟
    long s_time_for_test = 1553091900 ;
    long e_time_for_test = 1553094950;

    HashMap lastPoints= new HashMap<String , LatLng>();


    static AroundSearchResponse aroundSearchResponse_global = new AroundSearchResponse();





    //获取实例列表用
    EntityListRequest entityListRequest = new EntityListRequest(1 , serviceID );
    AroundSearchRequest aroundSearchRequest = new AroundSearchRequest(1 , serviceID);






    //搜索 添加 删除实例
    OnEntityListener onEntityListener = new OnEntityListener() {
        @Override
        public void onAddEntityCallback(AddEntityResponse addEntityResponse) {
            super.onAddEntityCallback(addEntityResponse);
            Log.d("捕捉到添加实例事件" , "信息:" + addEntityResponse.message);
        }

        @Override
        public void onUpdateEntityCallback(UpdateEntityResponse updateEntityResponse) {
            super.onUpdateEntityCallback(updateEntityResponse);
        }

        @Override
        public void onDeleteEntityCallback(DeleteEntityResponse deleteEntityResponse) {
            super.onDeleteEntityCallback(deleteEntityResponse);
        }
        /**
         * 请求实体列表的毁掉
         * @param entityListResponse
         * 含有设备当前的位置信息
         * allinfo为各种信息的聚合（使用自己的类提取信息）  但是不包含轨迹信息  仅包含当前的位置信息
         *   为当前的地图上全部的entity名
         */
        @Override
        public void onEntityListCallback(EntityListResponse entityListResponse) {
            super.onEntityListCallback(entityListResponse);

            int i = 0 ;


            boolean hasThisDevice = false;

            firstRun = false;

            if(entityListResponse.getEntities() != null)
            for(Iterator<EntityInfo> it = entityListResponse.getEntities().iterator(); it.hasNext();) {
                EntityInfo entityInfo = it.next();
                allinfo.add(entityInfo);
                enitynames.add(entityInfo.getEntityName());
                Log.d("i" , "获取到第" + (++i) + "个对象 " + entityInfo.getEntityName() );
                drawPoint(new LatLng(entityInfo.getLatestLocation().getLocation().latitude , entityInfo.getLatestLocation().getLocation().longitude) , entityInfo.getEntityName() , entityInfo);
            }
            else
            {
                Toast.makeText(mapAvtivity.this , "Fetal Error:信息获取失败" , Toast.LENGTH_LONG).show();
                finish();
            }




            for(Iterator<String> iterator = enitynames.iterator() ; iterator.hasNext();){

                String name = iterator.next();


                Log.d("i" , "正在请求" + name + "的轨迹");

                historyTrackRequest.setEntityName(name);

                if(!testMode) {
                    historyTrackRequest.setStartTime(System.currentTimeMillis() / 1000 - distanceTime);
                    historyTrackRequest.setEndTime(System.currentTimeMillis() / 1000);
                }
                else
                {
                    historyTrackRequest.setStartTime(s_time_for_test);
                    historyTrackRequest.setEndTime(e_time_for_test);
                    Log.e("1" , "正在使用测试模式请求历史轨迹");
                }


                //必备的  用于获取轨迹

                final LBSTraceClient client_ = client;

                client.queryHistoryTrack(historyTrackRequest , onTrackListener);




            }

            Log.d("i" , "EntityListCallback - 共获取到" + i + "个对象");

            enitynames.clear();
            Log.e("1" , "地图清理完成");

        }

        @Override
        public void onSearchEntityCallback(SearchResponse searchResponse) {
            super.onSearchEntityCallback(searchResponse);
        }

        @Override
        public void onBoundSearchCallback(BoundSearchResponse boundSearchResponse) {
            super.onBoundSearchCallback(boundSearchResponse);
        }

        @Override
        public void onAroundSearchCallback(AroundSearchResponse aroundSearchResponse) {
            super.onAroundSearchCallback(aroundSearchResponse);
            Log.e("e", "aroundSearchResponse回应信息:" + aroundSearchResponse.toString());

            ProcessOption processOption = new ProcessOption();
            processOption.setNeedMapMatch(true);
            processOption.setTransportMode(TransportMode.driving);

            if (!aroundSearchResponse.getEntities().isEmpty())
            {

                if(!testMode) {
                    historyTrackRequest.setStartTime(System.currentTimeMillis() / 1000 - distanceTime);
                    historyTrackRequest.setEndTime(System.currentTimeMillis() / 1000);
                }
                else
                {
                    historyTrackRequest.setStartTime(s_time_for_test);
                    historyTrackRequest.setEndTime(e_time_for_test);
                }
                historyTrackRequest.setProcessed(bindRoad);
                historyTrackRequest.setProcessOption(new ProcessOption().setTransportMode(TransportMode.driving)
                        .setNeedMapMatch(true));


                aroundSearchResponse_global.setEntities(aroundSearchResponse.getEntities());

                Iterator<EntityInfo> all = aroundSearchResponse_global.getEntities().iterator();


                EntityInfo entityInfo_t = all.next();
                historyTrackRequest.setEntityName(entityInfo_t.getEntityName());
                client.queryHistoryTrack(historyTrackRequest,onTrackListener);
                all.remove();

            }
            else
            {
                    final LocRequest locRequest = new LocRequest(serviceID);
                        try {

                            client.queryRealTimeLoc(locRequest, onEntityListener);
                            if(locRequest == null)
                                Log.e("fetal" , "locRequest id null");
                            else if(client == null)
                                Log.e("fetal" , "client id null");
                            else if(onEntityListener == null)
                                Log.e("fetal" , "onEntityListener id null");
                        }catch (Exception e)
                        {
                            Log.e("neewthread error" , e.getMessage()  );
                            Toast.makeText(mapAvtivity.this , "Fetal Error " , Toast.LENGTH_SHORT).show();
                        }
            }


            entitycounts = 2;

        }

        @Override
        public void onPolygonSearchCallback(PolygonSearchResponse polygonSearchResponse) {
            super.onPolygonSearchCallback(polygonSearchResponse);
        }

        @Override
        public void onDistrictSearchCallback(DistrictSearchResponse districtSearchResponse) {
            super.onDistrictSearchCallback(districtSearchResponse);
        }

        @Override
        public void onReceiveLocation(TraceLocation traceLocation) {
            super.onReceiveLocation(traceLocation);
            if(traceLocation.getLatitude() != 0)
                drawPoint(new com.baidu.trace.model.LatLng(traceLocation.getLatitude() , traceLocation.getLongitude()),thisDevice ,  traceLocation.getSpeed() );
            Log.e("addr" , ""+traceLocation.getLatitude() + "   " + traceLocation.getLongitude()) ;
            //client.stopRealTimeLoc();

        }
    };

    //用于获取历史轨迹
    HistoryTrackRequest historyTrackRequest = new HistoryTrackRequest(1 , serviceID);
    OnTrackListener onTrackListener = new OnTrackListener() {
        @Override
        public void onAddPointCallback(AddPointResponse addPointResponse) {
            super.onAddPointCallback(addPointResponse);
        }

        @Override
        public void onAddPointsCallback(AddPointsResponse addPointsResponse) {
            super.onAddPointsCallback(addPointsResponse);
        }

        /**
         * 用于提取历史轨迹
         * 提示除了历史轨迹
         *
         * @param historyTrackResponse
         */
        @Override
        public void onHistoryTrackCallback(final HistoryTrackResponse historyTrackResponse) {
            super.onHistoryTrackCallback(historyTrackResponse);


            Log.e("1" , "processing device " + historyTrackResponse.getEntityName());



                            double speed = 1.11;
                            int i = 0 ;
                            ArrayList<LatLng> points = new ArrayList<LatLng>();
                            for(Iterator<TrackPoint> it = historyTrackResponse.getTrackPoints().iterator(); it.hasNext();) {

                                Log.d("1" , "Drawing regular point");
                                TrackPoint trackPoint = it.next();

                                points.add(new LatLng(trackPoint.getLocation().latitude , trackPoint.getLocation().longitude ));

                                Log.w("time" , trackPoint.getLocTime() + " ");
                                i++;
                                //if(historyTrackResponse.getEntityName().equals(thisDevice) )
                                {
                                    speed = trackPoint.getSpeed();
                                    Log.w("1" , "speed updated to " + speed);
                                }



                            }

                            //if(historyTrackResponse.getEntityName().equals(thisDevice))
                            //{
                                drawPoint(historyTrackResponse.getEndPoint().getLocation() , historyTrackResponse.getEntityName() , speed);
                            //}else
                            //{

                            //}

                            Log.d("1" , "实体 " + historyTrackResponse.getEntityName() + " 的轨迹点共有" +
                                    + i + " 个");
                            if(points.size() >= 2)
                                DrawLine(points , historyTrackResponse.getEntityName());
                            else
                                Log.i("1" , "获取到的" + historyTrackResponse.getEntityName() + "的点小于两个：" + points.size() + " , 不描绘");


            if(aroundSearchResponse_global != null && aroundSearchResponse_global.getEntities() != null)
                if(!aroundSearchResponse_global.getEntities().isEmpty())
                {


                    alldone = false;
                    Iterator<EntityInfo> infoes = aroundSearchResponse_global.getEntities().iterator();
                    EntityInfo entityInfo_ = infoes.next();
                    historyTrackRequest.setEntityName(entityInfo_.getEntityName());
                    Log.e("1" , "started new thread in onhistorycallback - " + entityInfo_.getEntityName());
                    infoes.remove();
                    client.queryHistoryTrack(historyTrackRequest , onTrackListener);
                }else
                {
                    alldone = true;
                }
            else
            {

            }


        }

        @Override
        public void onDistanceCallback(DistanceResponse distanceResponse) {
            super.onDistanceCallback(distanceResponse);
        }

        @Override
        public void onLatestPointCallback(LatestPointResponse latestPointResponse) {
            super.onLatestPointCallback(latestPointResponse);

            if(latestPointResponse.getLatestPoint().getLocation().getLatitude() !=0
                    && latestPointResponse.getLatestPoint().getLocation().getLongitude() != 0)
            {
                if(latestPointResponse.getEntityName().equals(thisDevice))
                    drawPoint(latestPointResponse.getLatestPoint().getLocation() ,
                            latestPointResponse.getEntityName() ,
                            latestPointResponse.getLatestPoint().getSpeed());

            }

        }

        @Override
        public void onQueryCacheTrackCallback(QueryCacheTrackResponse queryCacheTrackResponse) {
            super.onQueryCacheTrackCallback(queryCacheTrackResponse);
        }

        @Override
        public void onClearCacheTrackCallback(ClearCacheTrackResponse clearCacheTrackResponse) {
            super.onClearCacheTrackCallback(clearCacheTrackResponse);
        }

        @Override
        public int hashCode() {
            return super.hashCode();
        }

        @Override
        public boolean equals(Object obj) {
            return super.equals(obj);
        }

        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }

        @Override
        public String toString() {
            return super.toString();
        }

        @Override
        protected void finalize() throws Throwable {
            super.finalize();
        }
    };


    //条件过滤器
    FilterCondition filterCondition = new FilterCondition();


    Handler mHandler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //在这里执行定时需要的操作
            baiduMap.clear();
            Log.e("1" , "地图清理完成");
            Log.d("1" , "this device : " + thisDevice);
            mHandler.postDelayed(this, flashTime * 1000);
            queryList();        //该函数已经取出试题信息
            updatemytrace();

        }
    };

    void updatemytrace()
    {

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        Log.d("basic info" , "onCreat , calling SDKInitializer.initialize()");

        SDKInitializer.initialize(this.getApplication());
        Log.d("basic info" , "onCreat , calling setContentView");

        setContentView(R.layout.content_map_avtivity);

        //thisDevice = SystemUtil.getDeviceBrand().toLowerCase() + SystemUtil.getIMEI(this);
        thisDevice = SystemUtil.getIMEI(this);

        Log.d("1" , thisDevice);


        StatusService.setEntityName(thisDevice);

        if(!ServiceTool.isServiceWork(getApplicationContext() ,"services.TrackService" ))
        {
            Intent startIntent = new Intent(getApplicationContext() , TrackService.class);
            startService(startIntent);
        }


        IntentFilter intentFilter ;   //用于注册接收service广播
        intentFilter = new IntentFilter();
        intentFilter.addAction("mybroadcast.trackservice.start");
        registerReceiver(new TrackServiceRecv() , intentFilter);


        init();




        mapView = new MapView(mapAvtivity.this);

        mapView.showZoomControls(false);
        baiduMap = mapView.getMap();
        baiduMap.setMyLocationEnabled(true);
        relativeLayout = (RelativeLayout) findViewById(R.id.mapLayout);
        relativeLayout.addView(mapView);


        baiduMap.setCompassEnable(true);
        baiduMap.setMyLocationEnabled(true);
        allinfo = new ArrayList<>();
        enitynames = new ArrayList<>();
        trackPoints = new ArrayList<>();
        allEntityTracePoints = new ArrayList<>();

        floatingActionButton = (com.getbase.floatingactionbutton.FloatingActionButton)findViewById(R.id.starttrack_button);
        floatingActionButton.setVisibility(View.INVISIBLE);

    }

    /**
     * 挥之轨迹（采用折现的方式）
     */

    private void DrawLine(List points , String entityName)
    {
        OverlayOptions options;


        if(entityName.equals(thisDevice))
        {
             options = new PolylineOptions()
                    .dottedLine(false)
                    .color(0XAA07dc00)
                    .width(15)
                    .points(points);
        }
        else
        {
             options = new PolylineOptions()
                    .dottedLine(false)
                    .color(0xAAFF0000)
                    .width(15)
                    .points(points);
        }
        baiduMap.addOverlay(options);
        Log.e("1" , "正在绘制轨迹,对象：" + entityName + entityName.equals(thisDevice) + thisDevice);


    }

    /**
     * 跳转到设置界面
     * @param view                                                                                                                                 空间，
     */


    public void jumpOtherSettings(View view)
    {
        showSettingDialog();
    }


    //锁定自身位置
    public void locateMyLocation(View view)
    {
        lockMylocation = !lockMylocation;
    }


    //
    public void startGuide(View view)
    {
        mHandler.postDelayed(runnable, 1000);
        baiduMap.animateMapStatus(MapStatusUpdateFactory.zoomTo(20.5f));    //设置地图缩放级别
        baiduMap.clear();
        Log.e("1" , "地图清理完成");
    }


    /**
     * 获取实例列表。已经过滤too long 之前定位的，需要过滤圈外轨迹点
     */
    public void queryList()
    {
        //baiduMap.clear();

        Log.d("1", "\n当前系统时间戳：" + (System.currentTimeMillis()/1000 - distanceTime));

        if(testMode)
            filterCondition.setActiveTime(1553005500 );
        else
            filterCondition.setActiveTime( System.currentTimeMillis()/1000 - distanceTime );


        if(firstRun)
        {
            //entityListRequest.setFilterCondition(filterCondition);
            //firstRun = false;
            Log.i("1" , "初次运行定位，默认请求全部实例,并且不绘制轨迹");
            client.queryEntityList(entityListRequest , onEntityListener);
            //目的是找到自身当前位置，在下一个分支会用到
        }
        else
        {
            Log.i("1" , "非初次请求，只请求范围内实例");

            aroundSearchRequest.setCenter(mylocation);
            aroundSearchRequest.setRadius(aroundSearchRadius);
            aroundSearchRequest.setCoordTypeInput(CoordType.bd09ll);
            aroundSearchRequest.setFilterCondition(filterCondition);


            Log.d("i" , "-------------------------------------\n" +
                    aroundSearchRequest.toString() +
                    aroundSearchRequest.getCenter().toString()+
                    "------------------------------------------");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    client.aroundSearchEntity(aroundSearchRequest , onEntityListener);
                }
            }).start();



        }
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            trackService = ((TrackService.MyBinder) service).getMyService();
            Log.d("1" , "正在开启initpart");
            initPart();
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        baiduMap.setMyLocationEnabled(false);
    }

    private void init()
    {
        if(ServiceTool.isServiceWork(this,"services.StatusService"))        //若服务正在 运行
        {
            have_logged_in = StatusService.GetLoginStatus();
            Toast.makeText(this , "Login 值: " + have_logged_in , Toast.LENGTH_SHORT).show();
            Log.d("MainAct","服务正在运行,获取到的login值为" + have_logged_in);
        }
        else
        {

            Toast.makeText(this , "Service not running " , Toast.LENGTH_SHORT).show();
            Intent change = new Intent(this,LogIn.class);
            startActivity(change);
            finish();
        }

        if(!have_logged_in)
        {
            Intent change = new Intent(this,LogIn.class);
            startActivity(change);
            finish();
        }else {
            Log.d("1" , "Logged in , starting service");
            startService(new Intent(this , TrackService.class));
        }


    }


    public void initPart()
    {

        client = trackService.getClient();

        floatingActionButton.setVisibility(View.VISIBLE);

        client.initThreadPoolConfig(8, 16, 16);

        client.setCacheSize(300);


        Log.i("2","started");
    }

    public class TrackServiceRecv extends BroadcastReceiver
    {

        @Override
        public void onReceive(Context context, Intent intent) {
            Intent intent1 = new Intent(mapAvtivity.this, TrackService.class);
            bindService( intent1 , mConnection ,  Context.BIND_AUTO_CREATE);
        }
    }

    public void drawPoint(LatLng latLng , String drawEntityName , EntityInfo entityinfo)
    {

        Log.d("locationInfo" , "MyLocationInfo: " + mylocation.latitude + " , " + mylocation.longitude);
        DotOptions dotOptions = new DotOptions();
        CircleOptions circleOptions = new CircleOptions();

        int fontcolor;
        int fontsize;
        int bgc;

        if(new DataSplit(entityinfo.toString()).getSpeed() < speed_alert) {
            fontcolor = safe;
            bgc = 0xffffff00;
            fontsize = 30;
        }
        else
        {
            alert(entityinfo);
            fontcolor = overSpeed;
            bgc = 0xffe50000;
            fontsize  = 50;
        }
                //如果为当前设备，绘制绿色点
                if( drawEntityName.equals(thisDevice))
                {
                    dotOptions.center(latLng)
                            .visible(true)
                            .color(Color.GREEN)
                            .radius(10);

                    circleOptions.center(latLng)
                            .visible(true)
                            .stroke(new Stroke(3 , Color.GREEN))
                            .fillColor(0x03BBFFFF)
                            .radius((int) aroundSearchRadius);

                    baiduMap.addOverlay(circleOptions);
                    baiduMap.addOverlay(dotOptions);

                    if(lockMylocation)
                        baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(latLng));
                    if(latLng.latitude !=0 && latLng.longitude !=0 )
                        mylocation = new com.baidu.trace.model.LatLng(latLng.latitude , latLng.longitude);

                    if (show_thiscar)
                    {
                        //定义文字所显示的坐标点
                        LatLng llText = new LatLng(latLng.latitude+ 0.00005 , (float)(latLng.longitude) );
//构建文字Option对象，用于在地图上添加文字
                        OverlayOptions textOption = new TextOptions()

                                .bgColor(bgc)
                                .fontSize(fontsize)
                                .fontColor(fontcolor)
                                .text(String.valueOf(new DataSplit(entityinfo.toString()).getSpeed()))
                                .rotate(0)
                                .position(llText);
//在地图上添加该文字对象并显示
                        baiduMap.addOverlay(textOption);
                    }
                }
                else
                {

                    dotOptions.center(latLng)
                            .visible(true)
                            .color(Color.RED )
                            .radius(5);

                    if (show_all)
                    {
                        //显示数据
                        //定义文字所显示的坐标点
                        LatLng llText = new LatLng(latLng.latitude + 0.00005 , latLng.longitude);
//构建文字Option对象，用于在地图上添加文字
                        OverlayOptions textOption = new TextOptions()
                                .bgColor(0xffffffff)
                                .fontSize(30)
                                .fontColor(fontcolor)
                                .text(String.valueOf(new DataSplit(entityinfo.toString()).getSpeed()))
                                .rotate(0)
                                .position(llText);
//在地图上添加该文字对象并显示
                        baiduMap.addOverlay(textOption);
                    }
                    baiduMap.addOverlay(dotOptions);
                }
    }

    public void drawPoint(com.baidu.trace.model.LatLng latLng , String drawEntityName , double speed)
    {

        Log.d("locationInfo" , "MyLocationInfo: " + mylocation.latitude + " , " + mylocation.longitude);

        DotOptions dotOptions = new DotOptions();
        CircleOptions circleOptions = new CircleOptions();

        int fontcolor;
        int fontsize;
        int bgc;

        if(speed < speed_alert) {
            fontcolor = safe;
            bgc = 0xffffff00;
            fontsize = 30;
        }
        else
        {
            alert(speed , drawEntityName);
            fontcolor = overSpeed;
            bgc = 0xffe50000;
            fontsize  = 50;
        }
        //如果为当前设备，绘制绿色点
        if( drawEntityName.equals(thisDevice))
        {
            dotOptions.center(new LatLng(latLng.getLatitude() , latLng.getLongitude()))
                    .visible(true)
                    .color(Color.GREEN)
                    .radius(10);

            circleOptions.center(new LatLng(latLng.getLatitude() , latLng.getLongitude()))
                    .visible(true)
                    .stroke(new Stroke(3 , Color.GREEN))
                    .fillColor(0x03BBFFFF)
                    .radius((int) aroundSearchRadius);

            baiduMap.addOverlay(circleOptions);
            baiduMap.addOverlay(dotOptions);

            if(lockMylocation)
                baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(new LatLng(latLng.getLatitude() , latLng.getLongitude())));

            if(latLng.latitude !=0 && latLng.longitude !=0 )
            {
                mylocation = new com.baidu.trace.model.LatLng(latLng.latitude , latLng.longitude);
                Log.d("location" , "my location updated:" + latLng.toString());
            }

            if (show_thiscar)
            {
                //定义文字所显示的坐标点
                LatLng llText = new LatLng(latLng.latitude+ 0.00005 , (float)(latLng.longitude) );
//构建文字Option对象，用于在地图上添加文字
                OverlayOptions textOption = new TextOptions()

                        .bgColor(bgc)
                        .fontSize(fontsize)
                        .fontColor(fontcolor)
                        .text(String.valueOf(speed))
                        .rotate(0)
                        .position(llText);
//在地图上添加该文字对象并显示
                baiduMap.addOverlay(textOption);
            }
        }
        else
        {

            dotOptions.center(new LatLng(latLng.getLatitude() , latLng.getLongitude()))
                    .visible(true)
                    .color(Color.RED )
                    .radius(5);

            if (show_all)
            {
                //显示数据
                //定义文字所显示的坐标点
                LatLng llText = new LatLng(latLng.latitude + 0.00005 , latLng.longitude);
//构建文字Option对象，用于在地图上添加文字
                OverlayOptions textOption = new TextOptions()
                        .bgColor(0xffffffff)
                        .fontSize(30)
                        .fontColor(fontcolor)
                        .text(String.valueOf(speed))
                        .rotate(0)
                        .position(llText);
//在地图上添加该文字对象并显示
                baiduMap.addOverlay(textOption);
            }
            baiduMap.addOverlay(dotOptions);
        }
    }


    private void showSettingDialog()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Setting");
        //    通过LayoutInflater来加载一个xml的布局文件作为一个View对象
        View view = LayoutInflater.from(this).inflate(R.layout.settingdialog, null);
        //    设置我们自己定义的布局文件作为弹出框的Content
        builder.setView(view);

        final EditText radius = (EditText)view.findViewById(R.id.editText);
        final EditText time_1 = (EditText)view.findViewById(R.id.timeSpan);
        final EditText time_2 = (EditText)view.findViewById(R.id.flashTime);
        final EditText speed = (EditText)view.findViewById(R.id.speed_alert);
        final EditText newname = (EditText)view.findViewById(R.id.editText2);

        final CheckBox checkBox1 = (CheckBox)view.findViewById(R.id.show_thiscar);
        final CheckBox checkBox2 = (CheckBox)view.findViewById(R.id.show_all);

        final  Switch sw_ = (Switch)view.findViewById(R.id.switch1);
        final Switch sw_2 = (Switch)view.findViewById(R.id.switch2);

        final TextView textView = (TextView)view.findViewById(R.id.textView);

        sw_.setChecked(testMode);
        sw_2.setChecked(bindRoad);
        checkBox1.setChecked(show_thiscar);
        checkBox2.setChecked(show_all);
        if(testMode)
            newname.setVisibility(View.VISIBLE);
        else
            newname.setVisibility(View.INVISIBLE);

        textView.setText("          提示      \n" +
                        "   以上更改后务必点击确定按钮，留空表示不更改\n" +
                        "   开启道路绑定后会强行将轨迹绑定到道路上，可能会导致失真，请根据需求选择开启或者不开启。");


        builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                if(!TextUtils.isEmpty(radius.getText()) )
                aroundSearchRadius = Double.valueOf(String.valueOf(radius.getText()));
                //    将输入的用户名和密码打印出来
                if(!TextUtils.isEmpty(time_1.getText()) )
                distanceTime = Long.valueOf(String.valueOf(time_1.getText()));

                if(!TextUtils.isEmpty(time_2.getText()) )
                flashTime = Integer.valueOf(String.valueOf(time_2.getText()));

                if(!TextUtils.isEmpty(speed.getText()) )
                    speed_alert = Integer.valueOf(String.valueOf(speed.getText()));

                if(!TextUtils.isEmpty(newname.getText()) )
                    thisDevice = String.valueOf(newname.getText());

                show_all = checkBox2.isChecked();
                show_thiscar = checkBox1.isChecked();
                testMode = sw_.isChecked();
                bindRoad = sw_2.isChecked();

                Toast.makeText(mapAvtivity.this, "设置保存成功", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {

            }
        });
        builder.show();
    }


    void alert(EntityInfo entityInfo)
    {

        String name;
        if(entityInfo.getEntityName().equals(thisDevice))
            name = "您";
        else
            name = "您周围有设备";

        NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        if(Build.VERSION.SDK_INT >= 26)
        {
            //当sdk版本大于26
            String id = "channel_2";
            String description = "本通知用于预警，请务必启用";
            int importance = NotificationManager.IMPORTANCE_MAX;
            NotificationChannel channel = new NotificationChannel(id, description, importance);

            manager.createNotificationChannel(channel);
            Notification notification = new Notification.Builder(getApplicationContext())
                    .setCategory(Notification.CATEGORY_MESSAGE)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("超速预警")
                    .setContentText(name + "超速（" + String.valueOf(new DataSplit(entityInfo.toString()).getSpeed()) + "km/h)运行中；")
                    .setAutoCancel(true)
                    .setChannelId(id)
                    .build();
            notification.flags |= Notification.FLAG_AUTO_CANCEL;

            manager.notify(2, notification);
        }
        else
        {

            //当sdk版本小于26
            Notification notification = new NotificationCompat.Builder(this)
                    .setContentTitle("超速预警")
                    .setContentText(name + "超速（" + String.valueOf(new DataSplit(entityInfo.toString()).getSpeed()) + "km/h)运行中；")
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.drawable.ic_launcher_foreground)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher_foreground))
                    .build();

            notification.flags |= Notification.FLAG_AUTO_CANCEL;

            manager.notify(2,notification);
        }
    }

    void alert(double speed , String entityName)
    {

        String name;
        if(entityName.equals(thisDevice))
            name = "您";
        else
            name = "您周围有设备";

        NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        if(Build.VERSION.SDK_INT >= 26)
        {
            //当sdk版本大于26
            String id = "channel_2";
            String description = "本通知用于预警，请务必启用";
            int importance = NotificationManager.IMPORTANCE_MAX;
            NotificationChannel channel = new NotificationChannel(id, description, importance);

            manager.createNotificationChannel(channel);
            Notification notification = new Notification.Builder(getApplicationContext())
                    .setCategory(Notification.CATEGORY_MESSAGE)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("超速预警")
                    .setContentText(name + "超速（" + String.valueOf(speed) + "km/h)运行中；")
                    .setAutoCancel(true)
                    .setChannelId(id)
                    .build();
            notification.flags |= Notification.FLAG_AUTO_CANCEL;

            manager.notify(2, notification);
        }
        else
        {

            //当sdk版本小于26
            Notification notification = new NotificationCompat.Builder(this)
                    .setContentTitle("超速预警")
                    .setContentText(name + "超速（" + String.valueOf(speed) + "km/h)运行中；")
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.drawable.ic_launcher_foreground)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher_foreground))
                    .build();

            notification.flags |= Notification.FLAG_AUTO_CANCEL;

            manager.notify(2,notification);
        }
    }


    void queryhistory(final ArrayList names , int size)
    {
        Runnable[] runnables = new Runnable[size];
        Handler handler = new Handler();
        int start = 0;
        int i = 0;
        for(Iterator<ArrayList<String>> it = names.iterator() ; it.hasNext(); )
        {
            final int count = i;
            //final String name = it.next();
            runnables[i] = new Runnable() {
                @Override
                public void run() {
                  //  historyTrackRequest.setEntityName(name);
                    client.queryHistoryTrack(historyTrackRequest , onTrackListener);
                }
            };

            handler.postDelayed(runnables[i] , start);
            start += 200;
            i++;

        }
    }


    void DrawMyLastPoint()
    {

    }


}
